package logic

import (
	"context"
	"fmt"
	"mall_srv/models/cache"
	"mall_srv/models/mysql"

	"mall_srv/internal/svc"
	"mall_srv/mall"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopAddLogic {
	return &ShopAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 购物车添加
func (l *ShopAddLogic) ShopAdd(in *mall.ShopAddRequest) (*mall.ShopAddResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var s mysql.Shop
	if err = s.GetShopById(int(in.ShopId)); err != nil {
		return nil, err
	}

	if s.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}

	if s.Stock < int(in.Num) {
		return nil, fmt.Errorf("商品库存不足")
	}

	key := fmt.Sprintf("cart:%d:%d", in.UserId, in.ShopId)
	exists := cache.Rdb.Exists(l.ctx, key).Val()
	fmt.Println("商品是否已经在购物车中", exists)

	if exists == 1 {
		fmt.Println("商品已经在购物车中")

		if err = cache.Rdb.HIncrBy(l.ctx, key, "num", in.Num).Err(); err != nil {
			return nil, err
		}
	} else {
		fmt.Println("商品不在购物车中")
		shopMap := map[string]interface{}{
			"shop_id": in.ShopId,
			"num":     in.Num,
			"name":    s.Name,
			"price":   s.Price,
			"img":     s.Img,
			"stock":   s.Stock,
			"checked": 1,
		}
		cache.Rdb.HMSet(l.ctx, key, shopMap)
	}

	return &mall.ShopAddResponse{}, nil
}
